import { Nodes, dom } from '@knno/dom';
import { DATA } from '../symbol';
import { formStyle } from './form.css';

export function getColumns(colDef: string): number[] {
	const arr = colDef.split(',').map((s) => {
		let v = parseInt(s);
		if (isNaN(v)) v = 1;
		if (v < 1) v = 1;
		if (v > 8) v = 8;
		return v;
	});
	arr.sort();
	if (arr.length === 0) arr.push(1);
	if (arr[0] !== 1) {
		arr.unshift(1);
	}
	if (arr.length < 4) {
		const v = arr[arr.length - 1];
		arr.push(...Array(4 - arr.length).fill(v));
	}
	return arr.slice(0, 4);
}

export class Form extends Nodes {
	private [DATA]: { columns: number[] };
	constructor() {
		super(dom.div(formStyle));
		this[DATA] = { columns: [1, 2, 4, 4] };
		const resizeObserver = new ResizeObserver(() => {
			this.calculate();
		});
		resizeObserver.observe(this.elems()[0]);
	}

	private calculate() {
		const width = this.width();
		let cols: number;
		let mode: number;
		if (width > 1600) {
			// BIG SCREEN
			cols = this[DATA].columns[3];
			mode = 3;
		} else if (width > 1200) {
			// PC
			cols = this[DATA].columns[2];
			mode = 2;
		} else if (width > 680) {
			// PAD
			cols = this[DATA].columns[1];
			mode = 1;
		} else {
			// MOBILE
			cols = this[DATA].columns[0];
			mode = 0;
		}
		const s = this.attr('mode');
		const c = this.attr('cols');
		if (c !== cols + '' || s !== mode + '') {
			this.attr('cols', cols + '');
			this.attr('mode', mode + '');
			this.query(':scope>*').emit(new Event('formcolumnchanged'));
		}
		this.css('gridTemplateColumns', `repeat(${cols}, 1fr)`);
	}

	columns(value: string): this {
		this[DATA].columns = getColumns(value);
		this.calculate();
		return this;
	}
}

export function form(...className: string[]): Form {
	return new Form().addClass(...className);
}
